package com.wutianyi.servlet.upload;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.wutianyi.utils.NetUtils;

public class UploadBlobServlet extends HttpServlet {
	private static Logger logger = Logger.getLogger("UploadBlobServlet");
	/**
	 * 
	 */
	private static final long serialVersionUID = -279138497576427711L;
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String redirect = NetUtils.getParameterString(req, "redirect", "0");
		Map<String, List<BlobKey>> mapBlobs = BlobstoreServiceFactory.getBlobstoreService()
				.getUploads(req);
		
		List<BlobKey> blobs = null;
		
		if (mapBlobs.size() > 0) {
			for (List<BlobKey> bs : mapBlobs.values()) {
				blobs = bs;
				break;
			}
		}
		
		if (null != blobs && !blobs.isEmpty()) {
			BlobKey blobKey = blobs.get(0);
			
			if ("1".equals(redirect)) {
				resp.sendRedirect("/serve?blob-key=" + blobKey.getKeyString());
			} else {
				resp.setContentType("text/plain");
				logger.info("/serve?blob-key=" + blobKey.getKeyString());
				String post = "";
				if (req.getServerPort() != 80) {
					post = ":" + req.getServerPort();
				}
				resp.getWriter().print(
						req.getScheme() + "://" + req.getServerName() + req.getContextPath() + post
								+ "/serve?blob-key=" + blobKey.getKeyString());
			}
		}
	}
	
}
